﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Implement;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.ApproveCommand;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.ApproveCommandHandler
{
    /// <summary>
    /// 请假申请表显示-命令
    /// </summary>
    public class NewListLeaveModelCommandHandler : IRequestHandler<NewListLeaveModelCommand, APIPaing<ListLeaveModelDTOS>>
    {
        private readonly IBaseRepository<LeaveModel> leaveRepos;
        private readonly IBaseRepository<User> userRepos;
        private readonly IBaseRepository<LeaveRecordModel> leaverecordRepos;

        public NewListLeaveModelCommandHandler(IBaseRepository<LeaveModel> leaveRepos, IBaseRepository<User> userRepos, IBaseRepository<LeaveRecordModel> leaverecordRepos)
        {
            this.leaveRepos = leaveRepos;
            this.userRepos = userRepos;
            this.leaverecordRepos = leaverecordRepos;
        }

        public async Task<APIPaing<ListLeaveModelDTOS>> Handle(NewListLeaveModelCommand request, CancellationToken cancellationToken)
        {
            APIPaing<ListLeaveModelDTOS> result = new APIPaing<ListLeaveModelDTOS>();

            //var list = await leaveRepos.GetAll().Result.ToListAsync();
            //取到申请人以上的层级(包含自己)
            var roles = await userRepos.GetAll().Result.Where(x => x.LevelRoleId < request.LevelRoleId).ToListAsync();
            //层级数转换数组
            var rolestring = roles.Select(x => x.LevelRoleId).ToArray();
            //判断条件 可查看人(本人,上级所有领导 --(看不到未通过的) )
            //list = list.Where(x => x.UserId == request.UserId || (rolestring.Contains(x.LevelRoleId) && x.DepId == request.DepId)).ToList();
            //判断条件 可查看人(本人,上级所有领导 --(看不到未通过的) )
            //list = list.Where(x => x.UserId == request.UserId || (x.LevelRoleId == request.LevelRoleId && x.DepId == request.DepId && x.AppStatus != 3)).ToList();

            //添加上原因显示
            var list = from a in await leaverecordRepos.GetAll().Result.OrderByDescending(x=>x.RecordId).Where(x=>x.Reason != null).ToListAsync()
                       join b in await  leaveRepos.GetAll().Result.ToListAsync() on a.LeaveId equals b.LeaveId
                   select new ListLeaveModelDTOS
                   {
                       LeaveId = a.LeaveId,
                       UserId = a.UserId,
                       NickName = b.NickName,
                       DepId = b.DepId,
                       LeaveType = b.LeaveType,
                       LeavePeriod = b.LeavePeriod,
                       LeaveTime = b.LeaveId,
                       LeaveEndTime = b.LeaveEndTime,
                       LeaveReason = b.LeaveReason,
                       LeaveLeader = b.LeaveLeader,
                       AppStatus = b.AppStatus,
                       CreateTime = b.CreateTime,
                       LevelRoleId = b.LevelRoleId,
                       Reason = a.Reason ?? "",
                   };

            //判断条件 可查看人(本人,上级所有领导 --(看不到未通过的) )
            list = list.Where(x => x.UserId == request.UserId || (x.LevelRoleId == request.LevelRoleId && x.DepId == request.DepId && x.AppStatus != 3)).ToList();

            //////条件查询///////
            //申请人名称
            if (!string.IsNullOrEmpty(request.NickName))
            {
                list = list.Where(x => x.NickName.Contains(request.NickName)).ToList();
            }
            //审批状态
            if (request.AppStatus != null)
            {
                list = list.Where(x => x.AppStatus == request.AppStatus).ToList();
            }
            //创建时间查询
            if (request.StartTime != null && request.EndTime != null)
            {
                list = list.Where(x => x.CreateTime >= request.StartTime && x.CreateTime <= request.EndTime).ToList();
            }
            //总页数
            int toTalCount = list.Count();
            //分页数
            int toTalPage = (int)Math.Ceiling(toTalCount * 1.0 / request.TotalSize);
            //分页
            list = list.OrderByDescending(x => x.CreateTime).Skip((request.TotalIndex - 1) * request.TotalSize).Take(request.TotalSize).ToList();
            if (list.Count() < 0)
            {
                result.Code = APIEnum.查询失败;
                result.Msg = APIEnum.查询失败.ToString();
                result.TotalCount = toTalCount;
                result.TotalPage = toTalPage;
                result.Items = list.ToList();
            }
            else
            {
                result.Code = APIEnum.查询成功;
                result.Msg = APIEnum.查询成功.ToString();
                result.TotalCount = toTalCount;
                result.TotalPage = toTalPage;
                result.Items = list.ToList();
            }

            return await Task.FromResult(result);
        }
    }
}
